﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using Learun.Application.Base.SystemModule;
using Learun.Util;

namespace Learun.Application.Web.AppApi
{
    /// <summary>
    /// 附件接口
    /// </summary>
    [RoutePrefix("api/AnnexesApi")]
    [HandlerApiLogin(FilterMode.Enforce)]
    [TokenAuthorize]
    public class AnnexesApiController : WebApiControllerBase
    {
        private AnnexesFileIBLL annexesFileIBLL = new AnnexesFileBLL();

        /// <summary>
        /// 上传绘图配置文件（包括图层颜色 和 标注样式）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string DrawingConfigFileUpload()
        {
            string ServerPathInXml = Config.GetValue("DrawingConfigFile");
            try
            {
                HttpPostedFile file = HttpContext.Current.Request.Files["file"];//接收

                if (file == null)
                {
                    return "未选择文件";
                }
                string fileName = Path.GetFileName(file.FileName);//文件+后缀名
                int fileSize = file.ContentLength;
                Stream inputStream = file.InputStream;//文件流


                var virtualPath = string.Format("{0}/{1}", ServerPathInXml, fileName);
                string path = Path.GetDirectoryName(virtualPath);
                Directory.CreateDirectory(path); //创建文件夹

                if (!System.IO.File.Exists(virtualPath))
                {
                    using (var fileStream = File.Create(virtualPath))
                    {
                        inputStream.Seek(0, SeekOrigin.Begin);
                        inputStream.CopyTo(fileStream);
                    }



                }
            }
            catch (Exception ex)
            {
                return "failure";
            }
            return "已经上传到服务器。";
        }

        /// <summary>
        /// 查询绘图相关的配置文件
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult DrawingConfigFileList()
        {
            List<string> list = new List<string>();
            string ServerPathInXml = Config.GetValue("DrawingConfigFile");
            if (System.IO.Directory.Exists(ServerPathInXml))
            {
                foreach (var filepath in System.IO.Directory.GetFiles(ServerPathInXml))
                {
                    if (FileDownHelper.FileExists(filepath))
                    {
                        list.Add(filepath.Replace(ServerPathInXml + "\\", ""));
                    }
                }
            }

            return Success(list);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="FileName">文件名，需要后缀</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult DrawingConfigFileDownFile(string FileName)
        {
            try
            {
                string ServerPathInXml = Config.GetValue("DrawingConfigFile");
                if (System.IO.Directory.Exists(ServerPathInXml))
                {
                    if (FileDownHelper.FileExists(ServerPathInXml + "\\" + FileName))
                    {
                        FileDownHelper.DownLoadnew(ServerPathInXml + "\\" + FileName);
                    }

                }




                return Success("准备下载");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }



        /// <summary>
        /// POST上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string UploadFile()
        {
            string fileGuid = Guid.NewGuid().ToString();
            try
            {
                UserInfo userInfo = LoginUserInfo.Get();
                HttpPostedFile file = HttpContext.Current.Request.Files["file"];//接收
                if (file == null)
                {
                    return "未选择文件";
                }
                string fileName = Path.GetFileName(file.FileName);//文件后缀名
                int fileSize = file.ContentLength;
                Stream s = file.InputStream;//文件流

                annexesFileIBLL.SaveAnnexes(fileGuid, fileGuid, fileName, fileSize, s, userInfo, "");
            }
            catch (Exception ex)
            {
                return "failure";
            }
            return fileGuid;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileId">文件ID</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult DownFile(string fileId)
        {
            try
            {
                var data = annexesFileIBLL.GetEntity(fileId);
                string filepath = data.F_FilePath;
                log4net.LogManager.GetLogger("Info").Info("待下载的文件地址为：" + filepath);
                if (FileDownHelper.FileExists(filepath))
                {
                    FileDownHelper.DownLoadnew(filepath);
                }
                return Success("");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 根据文件夹ID获取第一个文件信息
        /// </summary>
        /// <param name="folderId">文件夹ID</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(AnnexesFileEntity))]
        public IHttpActionResult GetFileEntity(string folderId)
        {
            try
            {
                AnnexesFileEntity entity = new AnnexesFileEntity();
                var fileList = annexesFileIBLL.GetList(folderId).ToList();
                if (fileList != null && fileList.Count > 0)
                {
                    entity = fileList[0];
                }
                return Success(entity);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
    }
}